import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/utils/util.dart';
import 'package:yp/widgets/bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
import 'package:yp/Xwidgets/ad_box.dart';
import 'package:yp/Xwidgets/button_widget.dart';
import 'package:yp/Xwidgets/line.dart';
import 'package:yp/config/style.dart';
import 'package:yp/widgets/dialog.dart';
import 'package:yp/config/config.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../router.dart';
import 'group_detail_logic.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class Group_detailPage extends StatefulWidget {
  @override
  _Group_detailPageState createState() => _Group_detailPageState();
}

class _Group_detailPageState extends State<Group_detailPage> {
  final logic = Get.put(Group_detailLogic());
  final state = Get.find<Group_detailLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Config.mainColor,
        brightness: Brightness.light,
        iconTheme: IconThemeData(color: Colors.white),
        title: Text(
          "拼团详情",
          style: TextStyle(color: Colors.white, fontSize: 32.sp),
        ),
      ),
      body: GetBuilder<Group_detailLogic>(builder: (logic) {
        if (state.group_buy_item != null) {
          return Stack(children: [
            ListView(children: [
              Column(
                children: [
                  Adimg(),
                  line(20.w),
                  moneyBanner(),
                  titleText(),
                  line(20.w),
                  speci(),
                  line(20.w),

                  // 收货地址
                  _receiveAddress(),
                  // _distributionScopeView(),
                  (state.addressAllString.length > 0)
                      ? line(20.w)
                      : Container(),

                  popPin(),
                  line(20.w),
                  playText(),
                  line(130.w),
                  (state.deliveryType == 0) ? line(75.w) : Container(),
                ],
              ),
            ]),
            _overDeliveryTipView(),
            if (state.showTip)
              InkWell(
                onTap: () {
                  setState(() {
                    state.showTip = !state.showTip;
                  });
                },
                child: Container(
                  color: Colors.black45.withOpacity(.75),
                  child: Center(
                      child: Text(
                    "请点击右上角的'...'\n然后选择在浏览器打开",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                    ),
                    textAlign: TextAlign.center,
                  )),
                ),
              ),
            Positioned(
              //方法二
              bottom: 0,
              child: _bottomPay(),
            )
          ]);
        } else {
          return Container();
        }
      }),
    );
  }

  Widget Adimg() {
    return Container(
      height: 700.w,
      child: AdBox(
          aspectRatio: 1,
          adKey: 'Adv',
          height: 500.w,
          borderRadius: 0,
          margin: EdgeInsets.zero,
          imageList: state.imageList),
    );
  }

  ///底部支付按钮
  Widget _bottomPay() {
    return Container(
      color: Colors.white,
      width: 750.w,
      height: 100.w,
      child: Row(
        mainAxisAlignment: state.deliveryType == 1
            ? MainAxisAlignment.spaceAround
            : MainAxisAlignment.end,
        children: [
          // 超出配送范围
          _overDeliveryView(),

          // 不在配送范围判断
          state.deliveryType == 1
              ? (GestureDetector(
                  onTap: () {
                    if (kIsWeb) {
                      /// 跳转到app失败 进入下载页或者提示系统浏览器打开
                      Future.delayed(Duration(seconds: 1), () {
                        if (isWechat()) {
                          // toast('请在系统浏览器打开本页面');
                          // Navigator.of(context).pop();
                          setState(() {
                            state.showTip = true;
                          });
                        } else {
                          /// 进入下载页
                          webpay(Config.WEB_DOWN_URL +
                              "download.html?g_buy_id=" +
                              state.arguments['g_buy_id'].toString());
                        }
                      });
                      webpay("yinpinhui://zrhsh.com/app?g_buy_id=" +
                          state.arguments['g_buy_id']);
                    } else {
                      Get.toNamed(RouteConfig.settleAccounts, arguments: {
                        'supply_unit_num_id':
                            state.group_buy_item['supply_unit_num_id'],
                        'g_buy_norm_num_id':
                            state.group_buy_item['g_buy_norm_num_id'],
                        'shop_id': state.group_buy_item['ec_shop_num_id'],
                        "item_num_id": state.group_buy_item['item_num_id'],
                        "style_num_id": state.group_buy_item['style_num_id'],
                        "ec_style_num_id":
                            state.group_buy_item['ec_style_num_id'],
                        'shopnum': 1
                      });
                    }
                  },
                  child: Container(
                    height: 100.w,
                    width: 375.w,
                    child: Center(
                        child: Text(
                      '直接购买:￥${state.click_buy_item_norms['price']}',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 32.sp),
                    )),
                  ),
                )

                  // 不在配送范围判断
                  )
              : (Container()),

          // 不在配送范围判断
          state.deliveryType == 1
              ? (state.group_buy_item['stock_qty'] != null &&
                          state.group_buy_item['stock_qty'] > 0 &&
                          state.group_buy_item['stock_type'] == 0
                      ? GestureDetector(
                          onTap: () {
                            YpBottomSheet.showSpecification(
                                context,
                                state.buy_item_norms,
                                state.group_buy_item, (bumNum, shopInfo) {
                              if (kIsWeb) {
                                /// 跳转到app失败 进入下载页或者提示系统浏览器打开
                                Future.delayed(Duration(seconds: 1), () {
                                  if (isWechat()) {
                                    // toast('请在系统浏览器打开本页面');
                                    // Navigator.of(context).pop();
                                    setState(() {
                                      state.showTip = true;
                                    });
                                  } else {
                                    /// 进入下载页
                                    webpay(Config.WEB_DOWN_URL +
                                        "download.html?g_buy_id=" +
                                        state.arguments['g_buy_id'].toString());
                                  }
                                });
                                webpay("yinpinhui://zrhsh.com/app?g_buy_id=" +
                                    state.arguments['g_buy_id'].toString());
                              } else {
                                // Get.toNamed(RouteConfig.settleAccounts, arguments: {
                                //   'shop_id': SpUtil.getInt('storeShopNum'),
                                //   "item_num_id": state.group_buy_item['item_num_id'],
                                //   "style_num_id": state.group_buy_item['style_num_id'],
                                //   "ec_style_num_id": state.group_buy_item['ec_style_num_id'],
                                //   'shopnum': bumNum.toDouble()
                                // }).then((value){
                                //   if (value != null) {
                                //     getCurrentLocationInfo(success: (data) {
                                //       var addressAllString =
                                //       data['addressAllString'];
                                //       var addressInfo = data['addressInfo'];
                                //       state.addressAllString = addressAllString;
                                //       state.addressInfo = addressInfo;
                                //       changeSelectAddress(addressInfo);
                                //       logic.onReady();
                                //     });
                                //   }
                                // });
                                Get.toNamed(RouteConfig.groupSettleAccounts,
                                    arguments: {
                                      'supply_unit_num_id': state
                                          .group_buy_item['supply_unit_num_id'],
                                      'g_buy_norm_num_id':
                                          shopInfo['g_buy_norm_num_id'],
                                      'shop_id': state
                                          .group_buy_item['ec_shop_num_id'],
                                      "item_num_id":
                                          state.group_buy_item['item_num_id'],
                                      "g_buy_id": shopInfo['g_buy_id'],
                                      "style_num_id":
                                          state.group_buy_item['style_num_id'],
                                      "ec_style_num_id": state
                                          .group_buy_item['ec_style_num_id'],
                                      'shopnum': bumNum.toDouble()
                                    }).then((value) {
                                  if (value != null) {
                                    getCurrentLocationInfo(success: (data) {
                                      var addressAllString =
                                          data['addressAllString'];
                                      var addressInfo = data['addressInfo'];
                                      state.addressAllString = addressAllString;
                                      state.addressInfo = addressInfo;
                                      changeSelectAddress(addressInfo);
                                      logic.onReady();
                                    });
                                  }
                                });
                              }
                            });
                          },
                          child: Container(
                            width: 375.w,
                            height: 100.w,
                            color: Colors.deepOrange,
                            child: Center(
                              child: Text(
                                  '我要开团:￥${state.click_buy_item_norms['g_buy_price']}',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      fontSize: 32.sp, color: Colors.white)),
                            ),
                          ),
                        )
                      : Container(
                          width: 375.w,
                          height: 100.w,
                          color: Colors.grey,
                          child: Center(
                            child: Text('暂无拼团优惠',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontSize: 32.sp, color: Colors.white)),
                          ),
                        )

                  // 不在配送范围判断
                  )
              : Container(),
        ],
      ),
    );
  }

  //价格和倒计时
  Widget moneyBanner() {
    return Container(
      padding: EdgeInsets.all(10.w),
      color: Colors.brown,
      width: MediaQuery.of(context).size.width,
      height: 80.w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
            Text(
              '￥',
              style: TextStyle(
                  color: Colors.white, fontSize: 24.sp, height: 2.4.w),
            ),
            Text(
              '${state.click_buy_item_norms['g_buy_price']}',
              style: TextStyle(
                  color: Colors.white, fontSize: 56.sp, height: 1.1.w),
            ),
            SizedBox(
              width: 10.w,
            ),
            Column(
              children: [
                Container(
                  child: Text(
                    '${state.group_buy_item['buy_qty']}件已售',
                    style: TextStyle(fontSize: 19.sp),
                  ),
                  //边框设置
                  decoration: new BoxDecoration(
                    color: Colors.white,
                    //设置四周圆角 角度
                    borderRadius: BorderRadius.all(Radius.circular(4.0)),
                  ),
                ),
                SizedBox(
                  height: 10.w,
                ),
                Text(
                  '单买:${state.click_buy_item_norms['price']}',
                  style: TextStyle(
                      decoration: TextDecoration.lineThrough,
                      fontSize: 19.sp,
                      color: Colors.white),
                )
              ],
            ),
          ]),
          Container(
            width: 300.w,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  '距离结束倒计时',
                  style: TextStyle(fontSize: 19.sp, color: Colors.orangeAccent),
                ),
                Text(
                  state.countContent,
                  style: TextStyle(fontSize: 20.sp, color: Colors.orangeAccent),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget titleText() {
    return Container(
      padding: EdgeInsets.all(10.w),
      child: Text(
        '${state.group_buy_item['g_buy_style_name']}',
        textAlign: TextAlign.start,
      ),
    );
  }

  Widget line(height) {
    return Container(
      height: height,
      width: MediaQuery.of(context).size.width,
      color: Colors.grey[200],
    );
  }

  //规格条
  Widget speci() {
    return GestureDetector(
      onTap: () {
        YpBottomSheet.showSpecification(
            context, state.buy_item_norms, state.group_buy_item,
            (bumNum, shopInfo) {
          print(bumNum);
          print(shopInfo);
          setState(() {
            state.click_buy_item_norms = shopInfo;
          });
        });
      },
      child: Container(
        height: 70.w,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(
                  width: 20.w,
                ),
                Text('规格'),
                SizedBox(
                  width: 20.w,
                ),
                Text(
                  '${state.click_buy_item_norms['norm_name']}',
                  style: TextStyle(color: Colors.deepOrange),
                )
              ],
            ),
            Icon(Icons.arrow_forward_ios)
          ],
        ),
      ),
    );
  }

  // 收货地址
  Widget _receiveAddress() {
    return Visibility(
      visible: (state.addressAllString.length > 0),
      child: Container(
        padding: EdgeInsets.only(left: 10, top: 0, right: 10, bottom: 0),
        child: Row(
          children: [
            Text('送至'),
            Expanded(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      state.addressAllString,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 14,
                        // color: Config.mainColor,
                      ),
                    ),
                    _distributionScopeView(),
                  ],
                ),
              ),
            ),
            IconButton(
                onPressed: () {
                  // Get.toNamed(RouteConfig.addressList);
                  Get.toNamed(RouteConfig.addressList).then((value) {
                    if (value != null) {
                      // changeSelectAddress(value["address"]);
                      logic.onReady();
                      // logic.getAddressInfo(finished:(backInfo) {
                      //   logic.requestDetail();
                      // });
                    }
                  });
                },
                icon: Image.asset(
                  'assets/images/more.png',
                  width: 20,
                  height: 6,
                )),
          ],
        ),
      ),
    );
  }

  // 配送范围
  Widget _distributionScopeView() {
    if (state.deliveryType == 0) {
      return Text(
        '无货，该商品在该地区暂不支持销售',
        style: TextStyle(
          fontSize: 12,
          color: const Color(0xFFAAAAAA),
        ),
      );
    } else {
      return Text(
        '现货',
        style: TextStyle(
          fontSize: 12,
          color: Colors.red,
        ),
      );
    }
  }

  // 超出配送范围
  Widget _overDeliveryView() {
    return Visibility(
      visible: (state.deliveryType == 0),
      child: Container(
        height: 38,
        padding: EdgeInsets.symmetric(horizontal: 8),
        margin: EdgeInsets.only(right: 8),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Color(0xFFE89E42),
          borderRadius: BorderRadius.all(
            Radius.circular(19),
          ),
        ),
        child: Text(
          '超出配送范围',
          style: TextStyle(
            fontSize: 14,
            color: Colors.white,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  // 超出配送范围-提示
  Widget _overDeliveryTipView() {
    return Visibility(
      visible: (state.deliveryType == 0),
      child: Positioned(
        //方法二
        bottom: 100.w,
        child: Container(
          width: 750.w,
          height: 80.w,
          padding: EdgeInsets.symmetric(horizontal: 8),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: Color(0xFFFCF9DF),
            // borderRadius: BorderRadius.all(
            //   Radius.circular(19),
            // ),
          ),
          child: Text(
            '所选地区暂时无货，非常抱歉！',
            style: TextStyle(
              fontSize: 14,
              color: Color(0xFFE89E42),
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }

  //拼团人数
  Widget popPin() {
    return Visibility(
      visible: state.codes.length > 0,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: GestureDetector(
              onTap: () {
                YpShowDialog.dialog(
                    context,
                    Material(
                        type: MaterialType.transparency,
                        child: Container(
                            decoration: BoxDecoration(
                                color: EsColors.White,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10))),
                            padding: EdgeInsets.symmetric(horizontal: 10),
                            constraints: BoxConstraints(
                                minHeight:
                                    MediaQuery.of(context).size.height / 3,
                                maxHeight:
                                    MediaQuery.of(context).size.height / 2),
                            child: ListView.separated(
                                shrinkWrap: true,
                                itemBuilder: (context, index) {
                                  if (state.codes[index]['g_buy_size'] -
                                          state.codes[index]
                                              ['g_buy_join_size'] >
                                      0) {
                                    return popItem(state.codes[index]);
                                  } else {
                                    return Container();
                                  }
                                },
                                separatorBuilder: (context, index) {
                                  return YpLine();
                                },
                                itemCount: state.codes.length))),
                    padding: const EdgeInsets.symmetric(horizontal: 10));
                // YpShowDialog.showGroupList(context);
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('已拼${state.group_buy_item['buy_qty']}人'),
                  Text('更多'),
                ],
              ),
            ),
          ),
          line(5.w),
          ListView.separated(
              shrinkWrap: true,
              itemBuilder: (context, index) {
                if (state.codes[index]['g_buy_size'] -
                        state.codes[index]['g_buy_join_size'] >
                    0) {
                  return popItem(state.codes[index]);
                } else {
                  return Container();
                }
              },
              separatorBuilder: (context, index) {
                return YpLine();
              },
              itemCount: state.codes.length >= 3 ? 3 : state.codes.length)
        ],
      ),
    );
  }

//拼团玩法
  Widget playText() {
    return GestureDetector(
      onTap: () {
        YpShowDialog.showActivitiesRule(context);
      },
      child: Container(
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.all(20.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '拼团玩法',
                    style: TextStyle(fontSize: 28.sp),
                  ),
                  Row(
                    children: [
                      Text(
                        '详情规则',
                        style:
                            TextStyle(fontSize: 18.sp, color: Colors.grey[400]),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: Colors.grey[400],
                      )
                    ],
                  )
                ],
              ),
            ),
            Image.asset('assets/images/huod.png')
          ],
        ),
      ),
    );
  }
}

class popItem extends StatefulWidget {
  Map cod;

  popItem(this.cod, {Key key}) : super(key: key);

  @override
  _popItemState createState() => _popItemState();
}

class _popItemState extends State<popItem> {
  final logic = Get.put(Group_detailLogic());
  final state = Get.find<Group_detailLogic>().state;
  // final StopWatchTimer _stopWatchTimerDown = StopWatchTimer(
  //   mode: StopWatchMode.countDown,
  //   presetMillisecond: StopWatchTimer.getMilliSecFromSecond(3),
  //   // onChange: (value) => print('onChange $value'),
  //   // onChangeRawSecond: (value) => print('onChangeRawSecond $value'),
  //   // onChangeRawMinute: (value) => print('onChangeRawMinute $value'),
  //   onEnded: () {
  //     print('onEnded');
  //   },
  // );
  var timer;
  int sec = 1668182399 - DateTime.now().millisecondsSinceEpoch ~/ 1000;
  String timeString = '';

  Widget _member(index, infos) {
    return Stack(
      children: [
        SizedBox(
          width: 70,
          height: 70,
        ),
        Positioned(
            width: 60,
            height: 60,
            child: ClipRRect(
                borderRadius: BorderRadius.circular(40),
                child: FadeInImage(
                    image: NetworkImage(index < infos.length
                        ? infos[index]['usr_logo']
                        : 'https://www.aa.com'),
                    imageErrorBuilder: (context, error, stackTrace) {
                      // TODO 图片加载错误后展示的 widget
                      // print("---图片加载错误---");
                      // 此处不能 setState
                      return Image.asset("assets/images/group_mumber.png");
                    },
                    placeholder: AssetImage('assets/images/group_mumber.png'),
                    fit: BoxFit.fill))),
        Positioned(
            bottom: 4,
            left: 18,
            child: Visibility(
              visible: true,
              child: Container(
                  decoration: BoxDecoration(
                      color: EsColors.Primary,
                      borderRadius: BorderRadius.circular(8)),
                  padding: EdgeInsets.fromLTRB(4, 1, 4, 1),
                  child: Text((index < 1) ? '团长' : '团员',
                      style: TextStyle(
                          color: EsColors.White,
                          fontSize: EsSizes.XXS,
                          fontWeight: EsFontWeights.Normal))),
            ))
      ],
    );
  }

  //加入弹窗
  joinshow(codes, headPop, int sec) {
    showDialog(
        context: context,
        // 点击空白收
        barrierDismissible: true,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context1, state1) {
            return Container(
              child: Material(
                  type: MaterialType.transparency,
                  child: Center(
                    child: IntrinsicHeight(
                      child: Container(
                          padding: EdgeInsets.all(50.w),
                          width: 600.w,
                          height: 500.w,
                          decoration: BoxDecoration(
                              color: EsColors.White,
                              borderRadius: BorderRadius.circular(10)),
                          child: Column(
                            children: [
                              textful(
                                  (codes['g_buy_size'] -
                                          codes['g_buy_join_size'])
                                      .toString(),
                                  sec),
                              SizedBox(
                                height: 20.w,
                              ),
                              Wrap(
                                  spacing: 0,
                                  children: List.generate(
                                      codes['g_buy_size'],
                                      (index) =>
                                          _member(index, codes['infos']))),
                              SizedBox(
                                height: 50.w,
                              ),
                              GestureDetector(
                                onTap: () {
                                  if (kIsWeb) {
                                    /// 跳转到app失败 进入下载页或者提示系统浏览器打开
                                    Future.delayed(Duration(seconds: 1), () {
                                      if (isWechat()) {
                                        // toast('请在系统浏览器打开本页面');
                                        // Navigator.of(context).pop();
                                        setState(() {
                                          state.showTip = true;
                                        });
                                      } else {
                                        /// 进入下载页
                                        webpay(Config.WEB_DOWN_URL +
                                            "download.html?g_buy_id=" +
                                            state.arguments['g_buy_id']
                                                .toString());
                                      }
                                    });
                                    webpay(
                                        "yinpinhui://zrhsh.com/app?g_buy_id=" +
                                            state.arguments['g_buy_id']);
                                  } else {
                                    Get.toNamed(RouteConfig.groupSettleAccounts,
                                        arguments: {
                                          'supply_unit_num_id':
                                              codes['supply_unit_num_id'],
                                          'g_buy_norm_num_id':
                                              codes['g_buy_norm_num_id'],
                                          'shop_id': codes['ec_shop_num_id'],
                                          "item_num_id": codes['item_num_id'],
                                          "g_buy_id": codes['g_buy_id'],
                                          "style_num_id": codes['item_num_id'],
                                          "ec_style_num_id": null,
                                          "g_buy_apply_id":
                                              codes['g_buy_apply_id'],
                                          'shopnum': 1
                                        }).then((value) {
                                      if (value != null) {
                                        getCurrentLocationInfo(success: (data) {
                                          var addressAllString =
                                              data['addressAllString'];
                                          var addressInfo = data['addressInfo'];
                                          state.addressAllString =
                                              addressAllString;
                                          state.addressInfo = addressInfo;
                                          changeSelectAddress(addressInfo);
                                          logic.onReady();
                                        });
                                      }
                                    });
                                  }
                                },
                                child: Container(
                                  width: 400.w,
                                  height: 100.w,
                                  decoration: BoxDecoration(
                                    color: Colors.deepOrange, // 背景色
                                    borderRadius:
                                        BorderRadius.circular((8)), // 圆角
                                  ),
                                  child: Center(
                                    child: Text(
                                      '加入团队',
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  ),
                                ),
                              )
                            ],
                          )),
                    ),
                  )),
            );
          });
        });
  }

  String date_format(micro_second) {
// 总秒数
    var second = (micro_second).floor();
// 天数
    var day = (second / 3600 / 24).floor();
// 小时
    var hr = (second / 3600 % 24).floor();
// 分钟
    var min = (second / 60 % 60).floor();
// 秒
    var secs = (second % 60).floor();

    return day.toString() +
        ":" +
        hr.toString() +
        ":" +
        min.toString() +
        ":" +
        secs.toString();
  }

  Map headPop;

  @override
  void initState() {
    widget.cod['infos'].forEach((element) {
      if (element['is_header'] == 1) {
        setState(() {
          headPop = element;
        });
      }
    });
    print('widget.cod');
    print(headPop['usr_name']);
    var _strtimes = DateTime.parse(widget.cod[
        'end_time']); //首先先将字符串格式的时间转为DateTime类型，因为millisecondsSinceEpoch方法转换要求为该格式
    var _intendtime = _strtimes.millisecondsSinceEpoch; //方法一
    sec = _intendtime ~/ 1000 - DateTime.now().millisecondsSinceEpoch ~/ 1000;
    const period = const Duration(seconds: 1);
    timer = Timer.periodic(period, (timer) {
      if (sec <= 0) {
        //倒计时秒数为0，取消定时器
        print('我被取消了  ');
        timer.cancel();
        // getData();
      }
      setState(() {
        timeString = date_format(sec);
        sec--;
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    /// 团内信息

    return Visibility(
      visible: widget.cod != null && headPop != null,
      child: Padding(
        padding: const EdgeInsets.only(left: 10, right: 10),
        child: Row(children: [
          Padding(
              padding: const EdgeInsets.only(top: 15, bottom: 15),
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(20),
                  child: FadeInImage(
                      image: NetworkImage(headPop['usr_logo']),
                      imageErrorBuilder: (context, error, stackTrace) {
                        // TODO 图片加载错误后展示的 widget
                        // print("---图片加载错误---");
                        // 此处不能 setState
                        return Image.asset("assets/images/group_mumber.png");
                      },
                      placeholder: AssetImage('assets/images/group_mumber.png'),
                      width: 40,
                      height: 40,
                      fit: BoxFit.fill))
              // child: Image.network(widget.cod['infos'][0]['usr_logo'], width: 45, height: 45, fit: BoxFit.fill),
              ),
          SizedBox(width: 1),
          Text(
            headPop['usr_name'].toString(),
            style: TextStyle(
                color: EsColors.TitleSecondary,
                fontSize: EsSizes.SM,
                fontWeight: EsFontWeights.Medium),
          ),
          Expanded(child: SizedBox()),
          Column(
            children: [
              RichText(
                  textAlign: TextAlign.center,
                  text: TextSpan(children: [
                    TextSpan(
                        text: '还差',
                        style: TextStyle(
                            fontSize: EsSizes.XS,
                            color: EsColors.TitleSecondary,
                            fontWeight: EsFontWeights.Normal)),
                    TextSpan(
                        text: (widget.cod['g_buy_size'] -
                                widget.cod['g_buy_join_size'])
                            .toString(),
                        style: TextStyle(
                            fontSize: EsSizes.XS,
                            color: EsColors.Primary,
                            fontWeight: EsFontWeights.Normal)),
                    TextSpan(
                        text: '人开团成功',
                        style: TextStyle(
                            fontSize: EsSizes.XS,
                            color: EsColors.TitleSecondary,
                            fontWeight: EsFontWeights.Normal)),
                  ])),
              Row(
                children: [
                  Text('剩余',
                      style: TextStyle(
                          fontSize: EsSizes.XS,
                          color: EsColors.Content,
                          fontWeight: EsFontWeights.Normal)),
                  SizedBox(
                    width: 73,
                    child: Center(
                      child: Text(timeString,
                          style: TextStyle(
                              fontSize: EsSizes.XS,
                              color: EsColors.Content,
                              fontWeight: EsFontWeights.Normal)),
                    ),
                  ),
                  Text('结束',
                      style: TextStyle(
                          fontSize: EsSizes.XS,
                          color: EsColors.Content,
                          fontWeight: EsFontWeights.Normal)),
                ],
              ),
            ],
          ),
          SizedBox(width: 8),
          EsOutLineButton(
            '去参团',
            bgColor: EsColors.Primary,
            textColor: EsColors.White,
            fontSize: EsSizes.MD,
            fontWeight: EsFontWeights.Medium,
            padding: EdgeInsets.symmetric(vertical: 6, horizontal: 12),
            borderRadius: 18,
            onTap: () {
              print('去参团');
              joinshow(widget.cod, headPop, sec);
              // Navigator.of(context).pop();
            },
          )
        ]),
      ),
    );
  }
}

class textful extends StatefulWidget {
  var popnum;
  int sec;

  textful(this.popnum, int this.sec, {Key key}) : super(key: key);

  @override
  _textfulState createState() => _textfulState();
}

class _textfulState extends State<textful> {
  var timer;
  String timeString = '0';

  String date_format(micro_second) {
// 总秒数
    var second = (micro_second).floor();
// 天数
    var day = (second / 3600 / 24).floor();
// 小时
    var hr = (second / 3600 % 24).floor();
// 分钟
    var min = (second / 60 % 60).floor();
// 秒
    var secs = (second % 60).floor();

    return day.toString() +
        ":" +
        hr.toString() +
        ":" +
        min.toString() +
        ":" +
        secs.toString();
  }

  @override
  void initState() {
    const period = const Duration(seconds: 1);
    timer = Timer.periodic(period, (timer) {
      if (widget.sec <= 0) {
        //倒计时秒数为0，取消定时器
        print('我被取消了  ');
        timer.cancel();
        // getData();
      }

      // print('倒计时');
      // print(sec);
      //更新界面
      //秒数减一，因为一秒回调一次
      setState(() {
        timeString = date_format(widget.sec);
        widget.sec--;
      });
    });
    super.initState();
    //   _stopWatchTimerDown.setPresetTime(mSec: null);
    // _stopWatchTimerDown.setPresetHoursTime(11);
    // _stopWatchTimerDown.setPresetMinuteTime(20);
    // _stopWatchTimerDown.setPresetSecondTime(12);
    // Future.delayed(Duration(milliseconds: 300), () {
    //   _stopWatchTimerDown.onExecute.add(StopWatchExecute.start);
    // });
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Text('还差${widget.popnum}人，${timeString}后结束');
  }
}
